#!/bin/bash
#
#  Copyright (c) 2020, The OpenThread Authors.
#  All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#  3. Neither the name of the copyright holder nor the
#     names of its contributors may be used to endorse or promote products
#     derived from this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
#  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
#  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#  POSSIBILITY OF SUCH DAMAGE.
#

set -euxo pipefail

# ==============================================================================
# Bash definitions

if [[ -n ${BASH_SOURCE[0]} ]]; then
    script_path="${BASH_SOURCE[0]}"
else
    script_path="$0"
fi
script_dir="$(realpath "$(dirname "${script_path}")")"
repo_dir="$(dirname "${script_dir}")"

# ==============================================================================
# shellcheck source=script/efr32-definitions
source "${repo_dir}/script/efr32-definitions"

# shellcheck source=script/util
source "${repo_dir}/script/util"

# ==============================================================================
OT_CMAKE_NINJA_TARGET=${OT_CMAKE_NINJA_TARGET-}

OT_OPTIONS=(
    "-DCMAKE_BUILD_TYPE=Release"
    "-DOT_DIAGNOSTIC=ON"
    "-DOT_EXTERNAL_HEAP=ON"
    "-DOT_PING_SENDER=ON"
    "-DOT_SLAAC=ON"
)

# Check if ccache is installed and use it if available
if command -v ccache >/dev/null; then
    OT_OPTIONS+=("-DCMAKE_C_COMPILER_LAUNCHER=ccache")
    OT_OPTIONS+=("-DCMAKE_CXX_COMPILER_LAUNCHER=ccache")
fi
readonly OT_OPTIONS

die()
{
    echo " ** ERROR: $1"
    exit 1
}

generate()
{
    if [ "${skip_generation}" = true ]; then
        return
    fi
    # Args
    local slcp_file="${1:?Please specify a SLCP file}"
    local generation_dir="${2:?Please specify generation directory}"
    shift 2

    set +x
    echo "========================================================================================================="
    echo "Generating ${slcp_file}"
    echo "========================================================================================================="
    set -x

    "${repo_dir}/script/generate" \
        "${slcp_file}" \
        "${generation_dir}" \
        "${board}"
}

build_example_app()
{
    set -x

    # Args
    local example_app_ninja_target="${1:?}"
    local slcp_file="${2:?}"
    shift 2

    # Parse the project name from the slcp file
    if [ ! -f "${slcp_file}" ]; then
        die "SLCP file not found: ${slcp_file}"
    fi
    local ot_platform_lib
    ot_platform_lib=$(grep -oP '(?<=project_name: ).*' "${slcp_file}" | tr -d '\r')

    # Generate the platform lib and related libs
    local generated_ot_platform_lib_dir=${slc_generated_projects_dir}/${ot_platform_lib}
    generate "${slcp_file}" "${generated_ot_platform_lib_dir}"

    # Create the build directory
    builddir="${OT_CMAKE_BUILD_DIR}/examples/${example_app_ninja_target}"
    mkdir -p "${builddir}"
    cd "${builddir}"

    # Configure and build the example app
    local ot_ftd=OFF
    if [[ ${example_app_ninja_target} == *-ftd ]]; then
        ot_ftd=ON
    fi
    local ot_mtd_ssed=OFF
    if [[ ${example_app_ninja_target} == *-mtd || ${example_app_ninja_target} == *-ssed ]]; then
        ot_mtd_ssed=ON
    fi
    cmake -GNinja \
        -DOT_COMPILE_WARNING_AS_ERROR=ON \
        -DOT_PLATFORM_LIB="${ot_platform_lib}" \
        -DOT_PLATFORM_LIB_DIR="${generated_ot_platform_lib_dir}" \
        -DOT_EXTERNAL_MBEDTLS="${ot_platform_lib}-mbedtls" \
        -DOT_RCP=OFF \
        -DOT_FTD=${ot_ftd} \
        -DOT_MTD=${ot_mtd_ssed} \
        -DOT_APP_CLI=OFF \
        -DOT_APP_NCP=OFF \
        -DOT_APP_RCP=OFF \
        "$@" \
        "${repo_dir}"
    ninja "${example_app_ninja_target}"

    create_srec "${builddir}"
    cd "${repo_dir}"
}

get_associated_cmake_app_option()
{
    local cmake_executable="${1:?Please specify a CMake executable target}"
    case "${cmake_executable}" in
        sleepy-demo-ftd)
            echo "EFR32_APP_SLEEPY_DEMO_FTD"
            ;;
        sleepy-demo-mtd)
            echo "EFR32_APP_SLEEPY_DEMO_MTD"
            ;;
        sleepy-demo-ssed)
            echo "EFR32_APP_SLEEPY_DEMO_SSED"
            ;;
        *)
            die "Unknown CMake executable: ${cmake_executable}"
            ;;
    esac
}

# Given a CMake executable name, return the associated SLCP file
get_associated_slcp()
{
    local cmake_executable="${1:?Please specify a CMake executable target}"

    case "${cmake_executable}" in
        sleepy-demo-ftd)
            echo "${repo_dir}/third_party/silabs/slc/platform_projects/openthread-efr32-soc-with-buttons.slcp"
            ;;
        sleepy-demo-mtd)
            echo "${repo_dir}/third_party/silabs/slc/platform_projects/openthread-efr32-soc-with-buttons-power-manager.slcp"
            ;;
        sleepy-demo-ssed)
            echo "${repo_dir}/third_party/silabs/slc/platform_projects/openthread-efr32-soc-with-buttons-power-manager-csl.slcp"
            ;;
        *)
            die "Unknown CMake executable: ${cmake_executable}"
            ;;
    esac
}

main()
{
    local usage="usage: $0 [-h] [--skip-silabs-apps] <brdXXXXy> [-D<OT_XXXX=ON> -D<OT_YYYY=OFF>]"

    skip_generation=false
    # Parse flags
    optspec=":h-:"
    while getopts "$optspec" optchar; do
        case "${optchar}" in
            -)
                case "${OPTARG}" in
                    skip-generation)
                        printf '\n\nSkipping SLC generation...\n\n' >&2
                        skip_generation=true
                        shift 1
                        ;;
                    *)
                        echo "Unknown option --${OPTARG}" >&2
                        exit 2
                        ;;
                esac
                ;;
            h)
                echo "${usage}" >&2
                exit 0
                ;;
        esac
    done

    # Parse board
    lowercase_args=$(echo "$@" | tr '[:upper:]' '[:lower:]')
    board=$([[ ${lowercase_args} =~ (brd[0-9]{4}[a-z]{1}) ]] && echo "${BASH_REMATCH[1]}")

    # Find component file for latest revision of board
    local board_slcc
    board_slcc=$(efr32_get_board_slcc "${board}")

    # Determine board's platform and exit if unsupported
    local platform
    platform=$(
        grep -Eo 'board:device:.*' "${board_slcc}" \
            | sed "s/board:device:${efr32_device_regex}/efr32\2\4/" \
            | head -n 1
    )
    if [ -z "$platform" ]; then
        echo "Error parsing platform"
        exit 3
    fi

    efr32_check_platform "${platform}" || die "Unsupported platform ${platform}"

    shift

    local options=("${OT_OPTIONS[@]}")

    options+=("-DCMAKE_TOOLCHAIN_FILE=src/${platform}/arm-none-eabi.cmake")

    options+=("$@")
    export OT_CMAKE_BUILD_DIR="$repo_dir/build/${board}"
    slc_generated_projects_dir="${OT_CMAKE_BUILD_DIR}"/slc

    # If no target is specified, build all targets
    if [ -z "${OT_CMAKE_NINJA_TARGET}" ]; then
        OT_CMAKE_NINJA_TARGET=(sleepy-demo-ftd sleepy-demo-mtd sleepy-demo-ssed)
    fi

    # Build the example apps
    for target in "${OT_CMAKE_NINJA_TARGET[@]}"; do
        build_example_app "${target}" "$(get_associated_slcp "${target}")" \
            -DEFR32_PLATFORM="${platform}" -DBOARD="${board}" "${options[@]}" -D"$(get_associated_cmake_app_option "${target}")"=ON
    done

    # List the built binaries
    for target in "${OT_CMAKE_NINJA_TARGET[@]}"; do
        if [ -d "${OT_CMAKE_BUILD_DIR}"/examples/"${target}" ]; then
            ls -alh "${OT_CMAKE_BUILD_DIR}"/examples/"${target}"/bin/*
        fi
    done
}

main "$@"
